package com.example.patchouli_knowledge

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.Image
import android.media.ImageReader
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Handler
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import android.view.WindowManager
import androidx.core.content.ContextCompat
import java.io.File
import java.io.FileOutputStream
import java.nio.ByteBuffer
import java.util.UUID

/**
 * 屏幕截图管理器，使用MediaProjection实现截屏功能
 */
class ScreenshotManager(private val context: Context) {
    companion object {
        private const val TAG = "ScreenshotManager"
        private const val VIRTUAL_DISPLAY_NAME = "screen-capture"
        
        // 存放截图请求结果的Intent，由Activity.onActivityResult设置
        var resultData: Intent? = null
        var resultCode: Int = 0
        var hasPermission: Boolean = false
        
        // 确保只有一个实例
        @Volatile
        private var instance: ScreenshotManager? = null
        
        fun getInstance(context: Context): ScreenshotManager {
            return instance ?: synchronized(this) {
                instance ?: ScreenshotManager(context).also { instance = it }
            }
        }
    }
    
    private var mediaProjection: MediaProjection? = null
    private var virtualDisplay: VirtualDisplay? = null
    private var imageReader: ImageReader? = null
    private val handler = Handler(Looper.getMainLooper())
    
    private var width: Int = 0
    private var height: Int = 0
    private var density: Int = 0
    
    private var screenshotCallback: ((String?) -> Unit)? = null
    
    init {
        // 获取屏幕尺寸和密度
        updateScreenMetrics()
    }
    
    /**
     * 更新屏幕尺寸和密度
     */
    private fun updateScreenMetrics() {
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val metrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(metrics)
        
        width = metrics.widthPixels
        height = metrics.heightPixels
        density = metrics.densityDpi
    }
    
    /**
     * 请求截图权限
     */
    fun requestCapturePermission(activity: Activity, requestCode: Int) {
        val mediaProjectionManager = context.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        activity.startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), requestCode)
    }
    
    /**
     * 准备媒体投影
     */
    fun prepareMediaProjection() {
        if (hasPermission && resultData != null) {
            val mediaProjectionManager = context.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
            mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, resultData!!)
        }
    }
    
    /**
     * 截取屏幕图像
     */
    fun captureScreen(callback: (String?) -> Unit) {
        screenshotCallback = callback
        
        if (mediaProjection == null) {
            prepareMediaProjection()
        }
        
        if (mediaProjection == null) {
            Log.e(TAG, "Media Projection未初始化，无法截图")
            callback(null)
            return
        }
        
        // 更新屏幕尺寸信息
        updateScreenMetrics()
        
        // 创建ImageReader
        imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2)
        imageReader?.setOnImageAvailableListener({ reader ->
            var image: Image? = null
            var bitmap: Bitmap? = null
            var fos: FileOutputStream? = null
            
            try {
                image = reader.acquireLatestImage()
                if (image != null) {
                    // 从Image创建Bitmap
                    val planes = image.planes
                    val buffer = planes[0].buffer
                    val pixelStride = planes[0].pixelStride
                    val rowStride = planes[0].rowStride
                    val rowPadding = rowStride - pixelStride * width
                    
                    bitmap = Bitmap.createBitmap(
                        width + rowPadding / pixelStride,
                        height,
                        Bitmap.Config.ARGB_8888
                    )
                    bitmap.copyPixelsFromBuffer(buffer)
                    
                    // 保存Bitmap到文件
                    val screenshotFile = createScreenshotFile()
                    fos = FileOutputStream(screenshotFile)
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
                    
                    // 回调返回文件路径
                    handler.post {
                        screenshotCallback?.invoke(screenshotFile.absolutePath)
                    }
                    
                    Log.d(TAG, "截图保存成功: ${screenshotFile.absolutePath}")
                } else {
                    handler.post {
                        screenshotCallback?.invoke(null)
                    }
                    Log.e(TAG, "获取图像失败")
                }
            } catch (e: Exception) {
                Log.e(TAG, "截图过程发生错误: ${e.message}")
                handler.post {
                    screenshotCallback?.invoke(null)
                }
            } finally {
                image?.close()
                bitmap?.recycle()
                fos?.close()
                tearDown()
            }
        }, handler)
        
        // 创建虚拟显示
        virtualDisplay = mediaProjection?.createVirtualDisplay(
            VIRTUAL_DISPLAY_NAME,
            width,
            height,
            density,
            DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            imageReader?.surface,
            null,
            handler
        )
        
        // 延迟1秒后截图，确保屏幕内容准备好
        handler.postDelayed({
            // 在某些设备上可能需要手动触发截图
            imageReader?.surface?.let { surface ->
                try {
                    virtualDisplay?.surface = null
                    virtualDisplay?.surface = surface
                } catch (e: Exception) {
                    Log.e(TAG, "手动触发截图失败: ${e.message}")
                }
            }
        }, 1000)
    }
    
    /**
     * 创建截图文件
     */
    private fun createScreenshotFile(): File {
        val timestamp = System.currentTimeMillis()
        val uuid = UUID.randomUUID().toString().substring(0, 8)
        val fileName = "screenshot_${timestamp}_$uuid.png"
        
        // 获取应用的文档目录
        val docDir = File(context.filesDir, "doc")
        if (!docDir.exists()) {
            docDir.mkdirs()
        }
        
        return File(docDir, fileName)
    }
    
    /**
     * 释放资源
     */
    private fun tearDown() {
        virtualDisplay?.release()
        virtualDisplay = null
        
        imageReader?.close()
        imageReader = null
        
        mediaProjection?.stop()
        mediaProjection = null
    }
} 